<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>新增借货返库订单</title>
<script type="text/javascript">
    Ext.onReady(function () {
        //此角色的最大折扣权限。        
        //是否临时保存
        var temporary = Ext.create('Ext.form.field.Hidden', {
            name:'temporary',
            value:0
        });

        var loanReturnedId = Ext.create('Ext.form.field.Hidden', {
            name:'id',
            value: <%=params[:id]%>
        });

        //所有仓库

        var toWarehouse = Ext.create('Ext.form.ComboBox', {
            store:warehouseStore,
            fieldLabel:'到仓库',
            allowBlank:false,
            blankText:"仓库必须选择",
            emptyText:'请选择...',
            valueField:'id',
            displayField:'name',
            name:'warehouse_id',
            loadingText:'搜索中...',
            anchor:'90%',
            //pageSize: 10,
            minChars:0,
            editable:false
        });

        //备注
        var desc = Ext.create('Ext.form.field.Text', {
            fieldLabel:'备注',
            name:'description',
            anchor:'100%'
        });

        //要求发货时间
        var actionDate = Ext.create('Ext.form.field.Date', {
            fieldLabel:'返库日期',
            name:'action_date',
            format:'Y-m-d', //格式化日期
            //disabledDays: [0,6],	//不让选择周六，周日
            //disabledDaysText: "周末要休息",
            invalidText:"您输入的日期格式不对，正确格式为2010-01-18",
            allowBlank:false,
            blankText:"返库日期必须选择",
            emptyText:'返库日期...'
            //anchor: '50%'
        });

        //--------------------------------------------------------------------------
        Ext.define('LoanReturnedDetailForEditModel', {
            extend:'Ext.data.Model',
            fields:[
                {
                    name:'id'
                },
                {
                    name:'number'
                },
                {
                    name:'name'
                },
                {
                    name:'description'
                },
                {
                    name:'quantity',
                    type:'int'
                },
                {
                    name:'balance_quantity',
                    type:'int'
                },
                {
                    name:'product_id'
                },
                {
                    name:'product_name'
                },
                {
                    name:'is_suit',
                    convert:function (value, record) {
                        if (value == "1") {
                            return "套装";
                        } else if (value == "0") {
                            return "单品";
                        }
                    }
                }
            ]
        });

        //借货返库订单列表Grid Store
        var loanDetailDS = Ext.create('Ext.data.Store', {
            //autoDestroy : true,
            model:'LoanReturnedDetailForEditModel',
            proxy:{
                type:'ajax',
                extraParams:{loan_returned_id:loanReturnedId.getValue()},
                url:'/loan_returned/getDetailsBalanceByIdForEdit',
                reader:{
                    type:'json',
                    root:'root',
                    totalProperty:'totalProperty'// 数据集记录总数
                }
            },
            autoLoad:true
        });


        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
            clicksToEdit:1
        });
        //生成要订单的产品的Grid
        var loanDetailGrid = Ext.create('Ext.grid.Panel', {
            store:loanDetailDS,
            plugins:[cellEditing],
            columns:[Ext.create('Ext.grid.RowNumberer'), {
                header:'产品名称',
                dataIndex:'product_name',
                width:290
            }, {
                header:'产品ID',
                dataIndex:'product_id',
                width:50,
                hidden:false
            }, {
                header:'产品编号',
                dataIndex:'number',
                width:100
            }, {
                header:'规格',
                dataIndex:'spec',
                width:50
            }, {
                header:'单位',
                dataIndex:'unit',
                width:40
            }, {
                header:'数量',
                align:'right',
                dataIndex:'quantity',
                field:Ext.create('Ext.form.field.Number', {
                    allowBlank:false,
                    allowDecimals:false,
                    minValue:1
                }),
                width:40
            }, {
                header:'套装或单品',
                dataIndex:'is_suit',
                width:70
            }, {
                header:'备注',
                dataIndex:'description',
                width:240,
                field:Ext.create('Ext.form.field.Text', {
                    name:'description',
                    anchor:'100%'
                })
            }],
            selModel:Ext.create('Ext.selection.CheckboxModel'),
            width:940,
            height:345,
            //frame: true,
            //title: '进货品种列表',
            //frame: true,
            //plugins: checkColumn,

            tbar:[
                {
                    text:'删除',
                    iconCls:'remove',
                    handler:function () {
                        var records = loanDetailGrid.getSelectionModel().getSelection();
                        cellEditing.cancelEdit();
                        loanDetailDS.remove(records);
                    }
                }
            ]
        });

        loanDetailGrid.on('edit', afterEdit, this);

        function afterEdit(editor, obj, options) {
            // execute an XHR to send/commit data to the server, in callback do (if successful):
            if (obj.field == "quantity") {
                if (obj.record.get('quantity') > obj.record.get('balance_quantity')) {
                    obj.record.set('quantity', obj.record.get('balance_quantity'));
                }
            }
        }

        //提交按钮
        var submitButton = Ext.create('Ext.Button', {
            text:'提交',
            tooltip:'保存并提交借货返库订单。',
            iconCls:'icon-save',
            handler:function () {
                //.setDisabled(true);
                //如果输入了首付金额，就要填写付款方式

                if (loanReturnedFormPanel.form.isValid()) {

                    var productsJsonStr = gridStoreToJson(loanDetailDS, rejectKeyArray);
                    if (loanDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title:'提示',
                            msg:"您还没有选择有效的产品或选择的产品数量为0！",
                            buttons:Ext.MessageBox.OK,
                            icon:Ext.MessageBox.INFO
                        });
                        return;
                    }
                    //没有添加产品，则提示
                    if (loanDetailDS.getCount() == 0 || productsJsonStr === "") {
                        Ext.MessageBox.show({
                            title:'提示',
                            msg:"您还没有选择有效的产品或选择的产品数量为0！",
                            buttons:Ext.MessageBox.OK,
                            icon:Ext.MessageBox.INFO
                        });
                        return;
                    }

                    this.disable();
                    var allJsonStr = loanReturnedFormPanel.getForm().getValues();
                    allJsonStr = Ext.JSON.encode(allJsonStr);
                    allJsonStr = Ext.util.Format.substr(allJsonStr, 0, allJsonStr.length - 1);
                    allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

                    Ext.Ajax.request({
                        url:'/loan_returned/update',
                        success:function (result, request) {
                            //Ext.MessageBox.alert("提示","提交成功");
                            editLoanReturnedWin.destroy();
                        },
                        failure:function (result, request) {
                            Ext.MessageBox.show({
                                title:'消息',
                                msg:"通讯失败，请从新操作",
                                buttons:Ext.MessageBox.OK,
                                icon:Ext.MessageBox.WARNING
                            });
                            editLoanReturnedWin.destroy();
                        },
                        method:'POST',
                        params:{
                            data:Ext.JSON.encode(allJsonStr),
                            authenticity_token:authToken.getValue()
                        }
                    });
                }
            }
        });

        //关闭按钮
        var closeButton = Ext.create('Ext.Button', {
            text:'关闭',
            tooltip:'关闭当前窗口，并且当前编辑的信息不能保存。',
            iconCls:'exit',
            handler:function () {
                editLoanReturnedWin.destroy();
            }
        });

        //采购申请的FormPanel
        var loanReturnedFormPanel = Ext.create('Ext.form.Panel', {
            fieldDefaults:{
                labelWidth:55,
                labelAlign:'right'
            },
            width:'950',
            frame:true,
            url:'/loan_returned/update',
            method:'GET',
            //defaultType: 'textfield',
            reader:Ext.create('Ext.data.reader.Json', {
                model:'LoanReturnedModel',
                root:'root'
            }),
            items:[
                {
                    layout:'column',
                    xtype:'container',
                    items:[
                        {
                            columnWidth:.3,
                            layout:'anchor',
                            xtype:'container',
                            items:[toWarehouse]
                        },
                        {
                            columnWidth:.2,
                            layout:'anchor',
                            xtype:'container',
                            items:[actionDate]
                        }
                    ]
                },
                {
                    layout:'column',
                    xtype:'container',
                    items:[
                        {
                            columnWidth:1,
                            layout:'anchor',
                            xtype:'container',
                            items:[desc]
                        }
                    ]
                },
                {
                    layout:'column',
                    xtype:'container',
                    items:[
                        {
                            columnWidth:1,
                            layout:'anchor',
                            xtype:'container',
                            items:[loanDetailGrid]
                        }
                    ]
                },
                temporary,
                loanReturnedId
            ],
            buttons:[submitButton, closeButton]
        });

        warehouseStore.load({callback:function (record, options, success) {
            if (success) {
                loanReturnedFormPanel.form.load({
                    url:'/loan_returned/getLoanReturnedById?id=' + <%=params[:id]%>,
                    method:'GET',
                    waitMsg:'正在载入数据...',
                    success:function (form, action) {
                    },
                    failure:function (form, action) {
                        Ext.MessageBox.alert('提示信息', '信息加载失败');
                    }
                });
            } else {
                Ext.MessageBox.alert('操作', '失败！');
            }
        }});

        loanReturnedFormPanel.render('edit_loan_returned');

    })
</script>
</head>
<body>
<div id="edit_loan_returned"></div>
</body>
</html>